var fs = require('fs')

function changeAppCode(file, app) {
  let indexHtml = fs.readFileSync(file, 'utf-8')
  let signal = '<meta name="APP_CODE" content="'
  let oldApp = indexHtml.substr(indexHtml.indexOf(signal)+signal.length, 2)
  let regexp = /(<meta name=\"APP_CODE\" content=\")+([a-z])+(\">)/
  // app与文件中的oldApp不同的时候，才重写文件
  if (app !== oldApp) {
    let html = indexHtml.replace(regexp,
      '<meta name="APP_CODE" content="' + app + '">'
    )
    fs.writeFileSync(file, html)
  }
}

function copyFileSync(src, dst) {
  fs.writeFileSync(dst, fs.readFileSync(src));
}

function readJson (filepath) {
  var str = fs.readFileSync(filepath).toString()
  // 去除注释
  str = str.replace(/\:\/\//g, '\:\\/\\/')
  str = str.replace(/\/\/[\s\S]*?\n/g, '')
  str = str.replace(/\/\/[\s\S]*?$/g, '')
  var res = false
  try {
    res = JSON.parse(str)
  } catch (ex1) {
    console.log(`json文件'${filepath}'解析错误`, ex1)
  }
  return res
}

function walkFile (ff, dataList) {
  let files = fs.readdirSync(ff)
  for (let fn in files) {
    let fname = ff + '/' + files[fn]
    let stat = fs.lstatSync(fname)
    if (stat.isDirectory() === true) {
      walkFile(fname, dataList)
    } else if (files[fn].match(/.(json)$/)) {
      dataList.push(fname)
    }
  }
}
function writeFile (text, path) {
  if (typeof text === 'object') text = JSON.stringify(text, null, '\t')
  path = process.cwd() + '/' + path + '.json'
  fs.writeFile(path, text, (err) => {
    err && console.log(err)
  })
}

module.exports = {
  changeAppCode,
  copyFileSync,
  walkFile,
  readJson,
  writeFile
}
